package com.yuqing.sentimentapp.module;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.linkface.baselibrary.utils.FileUtils;
import com.linkface.baselibrary.utils.ThreadManager;
import com.yuqing.sentimentapp.api.ApiService;
import com.yuqing.sentimentapp.interfaces.DownloadListener;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import io.reactivex.annotations.NonNull;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Description：下载文件工具类
 * Created by shenhe on 2019/5/8.
 */
public class DownloadPdfHelp {
    private static final String TAG = "DownloadPdfHelp";
    public static final String PATH_CHALLENGE_PDF = Environment.getExternalStorageDirectory() + "/DownloadFile";
    //视频下载相关
    protected ApiService mApi;
    private Call<ResponseBody> mCall;
    private File mFile;
    private String mPdfPath; //下载到本地的视频路径

    public DownloadPdfHelp(Context context) {
        if (mApi == null) {
            //初始化网络请求接口
            mApi = ModuleManager.getInstance().getApiService(context);
        }
    }

    public void downloadFile(String url, String name, final DownloadListener downloadListener) {
        //通过Url得到文件并创建本地文件
        mPdfPath = PATH_CHALLENGE_PDF + File.separator + name;
        //建立一个文件
        mFile = new File(mPdfPath);

        if (FileUtils.isFileExists(mFile)) {
            FileUtils.deleteSDDir(PATH_CHALLENGE_PDF);
        } else {
            mFile.getParentFile().mkdirs();
            try {
                mFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (TextUtils.isEmpty(mPdfPath)) {
            Log.e(TAG, "downloadVideo: 存储路径为空了");
            return;
        }

        if (mApi == null) {
            Log.e(TAG, "downloadVideo: 下载接口为空了");
            return;
        }
        mCall = mApi.downloadFileWithDynamicUrlAsync(url);
        downloadListener.onStart();
        mCall.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(@NonNull Call<ResponseBody> call, @NonNull final Response<ResponseBody> response) {
                Log.d(TAG, "downloadVideo: 正在下载。。。");
                ThreadManager.getThreadPollProxy().execute(new Runnable() {
                    @Override
                    public void run() {
                        //保存到本地
                        writeFile2Disk(response, mFile, downloadListener);
                    }
                });
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.e(TAG, "downloadVideo: 下载失败");
                downloadListener.onFailure(t.getMessage()); //下载失败
            }
        });
    }
    //将下载的文件写入本地存储
    private void writeFile2Disk(Response<ResponseBody> response, File file, DownloadListener downloadListener) {
//        downloadListener.onStart();
        long currentLength = 0;
        OutputStream os = null;

        InputStream is = response.body().byteStream(); //获取下载输入流
        long totalLength = response.body().contentLength();

        try {
            os = new FileOutputStream(file); //输出流
            int len;
            byte[] buff = new byte[1024];
            while ((len = is.read(buff)) != -1) {
                os.write(buff, 0, len);
                currentLength += len;
                Log.d(TAG, "当前进度: " + currentLength);
                //计算当前下载百分比，并经由回调传出
                downloadListener.onProgress((int) (100 * currentLength / totalLength));
                //当百分比为100时下载结束，调用结束回调，并传出下载后的本地路径
                if ((int) (100 * currentLength / totalLength) == 100) {
                    downloadListener.onFinish(mPdfPath); //下载完成
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close(); //关闭输出流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close(); //关闭输入流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
